Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

153
Visualizações
How to perform both a spread "operation" AND a callback function with useState in React

I am using functional components instead of class-based components. I have a state of hikes that is an array of objects and whenever I want to add a new hike to that array, I invoke the following line:

setCoors((coors=> [...coors, newCoor]))

But I also NEED to have the state callback function implemented. This is what Ive tried and it "sort of" works.

setCoors({coors:[...coors, newCoor]}, ()=>{console.log(coors)} )

But this is what I get back:

{
   coors:[
      0: {lat: 37.00, lng: -100.12},
      1: {lat: 88.00, lng: 76.12},
   ]
}

But i dont want my coor state to be an object...I need it to be an array like this:

{
   [
      0: {lat: 37.00, lng: -100.12},
      1: {lat: 88.00, lng: 76.12},
   ]
}

I can probably destructure the object to get what i want but I wanna know if there is an actual solution to this with setState. Does anyone have an idea of achieving this while also implementing a callback function? Thank you in advance

about 4 years ago · Santiago Trujillo
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda